import webbrowser

import paramiko
import os
import subprocess
from constant import *


# 远程服务器信息
remote_server = dev_remote_server

# 本地和远程文件路径
work_dir = const_work_dir
local_jar_path = const_local_jar_path + remote_server['dist_name']
remote_jar_path = remote_server['remote_jar_path']

os.chdir(work_dir)
process = subprocess.run(remote_server['command'],
                         shell=True,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE,
                         universal_newlines=True)
# print(f"命令输出:\n{process.stdout}")
if process.stderr:
    print(f"错误:\n{process.stderr}")


# 使用私钥进行SSH连接（如果有的话）
if remote_server['pkey']:
    private_key = paramiko.RSAKey.from_private_key_file(remote_server['pkey'])
else:
    private_key = None

# SSH连接到远程服务器
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(remote_server['host'], remote_server['port'], remote_server['username'], password=remote_server['password'],
            pkey=private_key)

# 使用SFTP上传dist目录下的所有文件到远程服务器
sftp = ssh.open_sftp()


def clear_remote_dir(remote_dir):
    try:
        files = sftp.listdir(remote_dir)
        for file in files:
            file_path = os.path.join(remote_dir, file)
            try:
                sftp.remove(file_path)
            except IOError:
                clear_remote_dir(file_path)
                sftp.rmdir(file_path)
    except FileNotFoundError:
        sftp.mkdir(remote_dir)


def upload_dir(local_dir, remote_dir):
    # 清空远程目录中的所有文件和子目录
    clear_remote_dir(remote_dir)

    for item in os.listdir(local_dir):
        local_path = os.path.join(local_dir, item)
        remote_path = os.path.join(remote_dir, item)

        if os.path.isdir(local_path):
            upload_dir(local_path, remote_path)
        else:
            sftp.put(local_path, remote_path)


upload_dir(local_jar_path, remote_jar_path)

sftp.close()
ssh.close()

webbrowser.open_new(remote_server['web_url'])


print(f"部署完成，稍等一分钟后访问")